package com.cxy.msclass.service;

import com.cxy.msclass.domain.dto.UserDTO;
import com.cxy.msclass.domain.entity.Lesson;
import com.cxy.msclass.domain.entity.LessonUser;
import com.cxy.msclass.repository.LessonRepository;
import com.cxy.msclass.repository.LessonUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class LessonService {
    @Autowired
    private LessonRepository lessonRepository;
    @Autowired
    private LessonUserRepository lessonUserRepository;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    public Lesson buyById(Integer id){
        //1.根据id查询lesson
        Lesson lesson= this.lessonRepository.findById(id).orElseThrow(()->new IllegalArgumentException("该课程不存在！"));
        //2. 根据lesson.id查询user_lesson,那么直接返回，如果没有
        LessonUser lessonUser=this.lessonUserRepository.findByLessonId(id);
        if(lessonUser!=null){
            return lesson;
        }
        //3.如果user_lesson==null &&用户余额>lesson.price，就购买
        //TODO  登录实现后需要重构
        Integer userId=1;
        List<ServiceInstance>instanceList=this.discoveryClient.getInstances("ms-user");
        List<ServiceInstance> jifang1 = instanceList.stream().filter(instance -> {
            //用户微服务元数据
            Map<String, String> metadata = instance.getMetadata();
            String jifang = metadata.get("JIFANG");
            if ("NJ".equals(jifang)) {
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        //TODO 需要改进
        URI uri = jifang1.get(0).getUri();
        UserDTO forObject = restTemplate.getForObject(uri+"/users/{userId}", UserDTO.class, userId);
        BigDecimal money=forObject.getMoney().subtract(lesson.getPrice());
        if(money.doubleValue()<0){
            throw new IllegalArgumentException("余额不足");
        }
        //TODO 购买逻辑。。。1.调用用户微服务的扣减金额接口；2.向lesson_user表插入数据
        return lesson;
    }
}
